package com.example.a_java.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.a_java.common.Result;
import com.example.a_java.dto.LoanApprovalDTO;
import com.example.a_java.entity.LoanApply;
import com.example.a_java.entity.LoanApproval;
import com.example.a_java.service.LoanApplyService;
import com.example.a_java.service.LoanApprovalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 贷款审批Controller
 */
@RestController
@RequestMapping("/loan/approval")
public class LoanApprovalController {

    @Autowired
    private LoanApprovalService loanApprovalService;
    
    @Autowired
    private LoanApplyService loanApplyService;

    /**
     * 获取待审批列表
     */
    @GetMapping("/pending")
    public Result<Map<String, Object>> pendingList(
            @RequestParam(required = false) String loanNo,
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        // 查询数据
        Page<LoanApply> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LoanApply> wrapper = new LambdaQueryWrapper<>();
        
        // 基本条件：状态为待审核或审核中
        wrapper.in(LoanApply::getApplyStatus, 10, 20);
        
        // 添加查询条件
        if (StringUtils.hasText(loanNo)) {
            wrapper.like(LoanApply::getApplyNo, loanNo);
        }
        
        if (StringUtils.hasText(customerName)) {
            wrapper.like(LoanApply::getCustomerName, customerName);
        }
        
        if (StringUtils.hasText(status)) {
            Integer statusCode = convertStatusToCode(status);
            if (statusCode != null) {
                wrapper.eq(LoanApply::getApplyStatus, statusCode);
            }
        }
        
        // 按创建时间降序排序
        wrapper.orderByDesc(LoanApply::getCreateTime);
        
        // 分页查询
        page = loanApplyService.page(page, wrapper);
        
        // 构造返回结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (LoanApply loanApply : page.getRecords()) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", loanApply.getApplyId());
            map.put("loanNo", loanApply.getApplyNo());
            map.put("customerName", loanApply.getCustomerName());
            map.put("loanAmount", loanApply.getLoanAmount());
            map.put("loanTerm", loanApply.getLoanTerm());
            map.put("purpose", loanApply.getLoanPurpose());
            map.put("status", convertCodeToStatus(loanApply.getApplyStatus()));
            map.put("currentNode", loanApply.getCurrentNode());
            map.put("submitTime", loanApply.getApplyTime());
            list.add(map);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("total", page.getTotal());
        result.put("list", list);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        
        return Result.success(result);
    }

    /**
     * 提交审批
     */
    @PostMapping
    public Result<Object> submit(@RequestBody @Valid LoanApprovalDTO approvalDTO) {
        // 检查贷款申请是否存在
        LoanApply loanApply = loanApplyService.getById(approvalDTO.getApplyId());
        if (loanApply == null) {
            return Result.error("贷款不存在");
        }
        
        // 检查状态是否允许审批
        if (loanApply.getApplyStatus() != 10 && loanApply.getApplyStatus() != 20) {
            return Result.error("贷款状态不允许此操作");
        }
        
        // 验证审批参数
        if ("approve".equals(approvalDTO.getDecision())) {
            if (approvalDTO.getApprovedAmount() == null) {
                return Result.error("批准的贷款金额不能为空");
            }
            
            if (approvalDTO.getLoanDate() == null) {
                return Result.error("放款日期不能为空");
            }
        }
        
        // 创建审批记录
        LoanApproval approval = new LoanApproval();
        approval.setApplyId(approvalDTO.getApplyId());
        approval.setNodeName("信贷审批"); // 示例节点，实际应根据当前流程节点设置
        approval.setApproverId(1L); // 示例审批人ID，实际应从当前登录用户获取
        approval.setApproverName("审批人"); // 示例审批人姓名，实际应从当前登录用户获取
        approval.setApproverRole("信贷经理"); // 示例审批人角色，实际应从当前登录用户获取
        approval.setDecision(approvalDTO.getDecision());
        approval.setApprovalOpinion(approvalDTO.getComment());
        approval.setApprovalTime(LocalDateTime.now());
        
        if ("approve".equals(approvalDTO.getDecision())) {
            approval.setApprovalType(1); // 通过
            approval.setApprovedAmount(approvalDTO.getApprovedAmount());
            approval.setLoanDate(approvalDTO.getLoanDate());
        } else {
            approval.setApprovalType(2); // 拒绝
        }
        
        // 更新贷款申请状态
        if ("approve".equals(approvalDTO.getDecision())) {
            loanApply.setApplyStatus(30); // 审核通过
            loanApply.setApprovalStatus("approved");
            loanApply.setApprovalComment(approvalDTO.getComment());
            loanApply.setApprovedAmount(approvalDTO.getApprovedAmount());
            loanApply.setLoanDate(approvalDTO.getLoanDate());
        } else {
            loanApply.setApplyStatus(40); // 审核拒绝
            loanApply.setApprovalStatus("rejected");
            loanApply.setApprovalComment(approvalDTO.getComment());
        }
        
        // 保存审批记录并更新贷款状态
        boolean success = loanApprovalService.save(approval) && loanApplyService.updateById(loanApply);
        
        if (success) {
            return Result.success("审批提交成功");
        } else {
            return Result.error("审批提交失败");
        }
    }

    /**
     * 获取审批历史
     */
    @GetMapping("/history/{applyId}")
    public Result<List<Map<String, Object>>> history(@PathVariable Long applyId) {
        // 检查贷款申请是否存在
        LoanApply loanApply = loanApplyService.getById(applyId);
        if (loanApply == null) {
            return Result.error("贷款不存在");
        }
        
        // 查询审批历史
        List<LoanApproval> approvals = loanApprovalService.list(
                new LambdaQueryWrapper<LoanApproval>()
                        .eq(LoanApproval::getApplyId, applyId)
                        .eq(LoanApproval::getIsDeleted, 0)
                        .orderByAsc(LoanApproval::getApprovalTime)
        );
        
        // 构造返回结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (LoanApproval approval : approvals) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", approval.getApprovalId());
            map.put("applyId", approval.getApplyId());
            map.put("approverName", approval.getApproverName());
            map.put("approverRole", approval.getApproverRole());
            map.put("nodeName", approval.getNodeName());
            map.put("decision", approval.getDecision());
            map.put("comment", approval.getApprovalOpinion());
            
            if (approval.getApprovedAmount() != null) {
                map.put("approvedAmount", approval.getApprovedAmount());
            }
            
            if (approval.getLoanDate() != null) {
                map.put("loanDate", approval.getLoanDate());
            }
            
            map.put("approvalTime", approval.getApprovalTime());
            list.add(map);
        }
        
        return Result.success(list);
    }
    
    /**
     * 转换状态字符串为状态码
     */
    private Integer convertStatusToCode(String status) {
        switch (status) {
            case "pending": return 10; // 待审核
            case "reviewing": return 20; // 审核中
            default: return null;
        }
    }
    
    /**
     * 转换状态码为状态字符串
     */
    private String convertCodeToStatus(Integer statusCode) {
        switch (statusCode) {
            case 10: return "pending"; // 待审核
            case 20: return "reviewing"; // 审核中
            case 30: return "approved"; // 审核通过
            case 40: return "rejected"; // 已拒绝
            default: return "pending";
        }
    }
} 
